package m202405.d17;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/5/17 14:46
 */
public class Q72 {

    public static void main(String[] args) {
        Q72 q72 = new Q72();
        q72.minDistance("horse","ros");
    }

    /**
     * 1.在w1中插入字符
     * 2.在w2中插入字符
     * 3.修改w1的一个字符
     * <p>
     * dp[i][j]表示w1的前i个字符和w2的前j个字符之间的编辑距离
     * dp[i][j] = min(dp[i-1][j]+1,dp[i][j-1],dp[i-1][j-1])  w1(i)==w2(j)
     * dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1  w1(i)!=w2(j)
     */
    public int minDistance(String word1, String word2) {
        int[][] dp = new int[word1.length() + 1][word2.length() + 1];
        for (int i = 1; i <= word1.length(); i++) {
            dp[i][0] = i;
        }
        for (int j = 1; j <= word2.length(); j++) {
            dp[0][j] = j;
        }
        for (int i = 1; i <= word1.length(); i++) {
            char c1 = word1.charAt(i - 1);
            for (int j = 1; j <= word2.length(); j++) {
                char c2 = word2.charAt(j - 1);
                if (c1 == c2) {
                    dp[i][j] = Math.min(dp[i - 1][j] + 1, Math.min(dp[i][j - 1] + 1, dp[i - 1][j - 1]));
                } else {
                    dp[i][j] = Math.min(dp[i - 1][j], Math.min(dp[i][j - 1], dp[i-1][j-1])) + 1;
                }
            }
        }
        return dp[word1.length()][word2.length()];
    }
}
